import { UniStore } from '@/utils/UniStorege'
import { StringUtils } from '@/utils/StringUtils'
import ENV from '@/build/env'

import { MicroService } from '@/build/MicroService'

export class RequestAPI {
  constructor(options = {}) {
    let { url = '', noBase = false, service = MicroService.COMMON } = options || {}
    const api = ENV[ENV.env_name].api
    this.ip = api
    this.base = '/'

    this.service = service + "/"
    this.suffix = ''
    this.base_url = [this.ip, this.base, this.service, url].join('')
    if (noBase) {
      this.base_url = ''
    }
    this.headerKey = 'Authorization'
    this.tokenSuffix = 'Bearer'
    this.header = {
      'Content-Type': 'application/json;charset=utf-8',
      // 'Access-Control-Allow-Origin': '*'
    }
  }

  _injects() {
    this.base_url = [this.ip, this.base, this.service].join('')

    this.injectToken()
  }

  injectToken() {
    let token_str = UniStore.getT()
    let token = this.joinToken(token_str)
    if (!StringUtils.isEmptyOrNull(token_str)) {
      this.header[this.headerKey] = token
    }
  }

  joinToken(token_string) {
    let _str = [this.tokenSuffix, token_string].join(' ')
    return _str.trim()
  }

  async get(url, params = {}) {
    this._injects()

    try {
      const _url = (this.base_url + url) || this.base_url
      console.log("[GET]{REQUEST} : ", this.service + url, "[params] -> ",params)
      let res = await uni.request({
        url:_url,
        method: 'GET',
        data: params,
        header: this.header
      })

      let { data } = res
      // if (Array.isArray(res)) {
      //   let [err, resData] = res || [];
      //   if (err) {
      //     errMsg = err.errMsg
      //   }
      //   data = errMsg || resData;
      // }

      return data
    } catch (err) {
      throw new Error(`错误:${err.errMsg}`)
    }
  }

  async post(url, params = {}) {
    this._injects()
    try {
      const _url = (this.base_url + url) || this.base_url
      console.log("[POST]{REQUEST} : ", this.service + url, "[params] -> ",params)
      let res = await uni.request({
        url:_url,
        method: 'POST',
        data: params,
        header: this.header
      })

      let { data } = res

      // if (Array.isArray(res)) {
      //   let [err, resData] = res || [];
      //   if (err) {
      //     errMsg = err.errMsg
      //   }
      //   data = errMsg || resData;
      // }
      //
      return data
    } catch (err) {
      throw new Error(`错误:${err.errMsg}`)
    }
  }

  async put(url, params = {}) {
    this._injects()
    try {
      let res = await uni.request({
        url: this.base_url + url || this.base_url,
        method: 'PUT',
        data: params,
        header: this.header
      })
      console.log('[request]->post', this.base_url + url, '[res]->', res)
      let { data } = res

      // if (Array.isArray(res)) {
      //   let [err, resData] = res || [];
      //   if (err) {
      //     errMsg = err.errMsg
      //   }
      //   data = errMsg || resData;
      // }
      //
      return data
    } catch (err) {
      throw new Error(`错误:${err.errMsg}`)
    }
  }

  async delete(url, params = {}) {
    this._injects()
    try {
      let res = await uni.request({
        url: this.base_url + url || this.base_url,
        method: 'DELETE',
        data: params,
        header: this.header
      })
      console.log('[request]->post', this.base_url + url, '[res]->', res)
      let { data } = res

      // if (Array.isArray(res)) {
      //   let [err, resData] = res || [];
      //   if (err) {
      //     errMsg = err.errMsg
      //   }
      //   data = errMsg || resData;
      // }
      //
      return data
    } catch (err) {
      throw new Error(`错误:${err.errMsg}`)
    }
  }

  async request(options = {}){
    let {
      url,
      method,
      service =  MicroService.COMMON,
      params,
      data
    } = options || {}
    let res
    this.service = `${service}/`
    const METHOD = method?.toUpperCase()
    if(METHOD === 'POST'){
      res = await this.post(url,params || data)
    }else if(METHOD === 'GET'){
      res = await this.get(url,params || data)
    }else if(METHOD === 'DELETE'){
      res = await this.delete(url,params || data)
    }else if(METHOD === 'PUT'){
      res = await this.put(url,params || data)
    }


    return res
  }
}
